package com.ybwh.outterapi;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ybwh.outterapi.codec.AppInfoAccesser;
import com.ybwh.outterapi.codec.DataCrypto;
import com.ybwh.outterapi.codec.DefaultDataCrypto;
import com.ybwh.outterapi.requst.HashCheckRequestInputStreamFilter;
import com.ybwh.outterapi.requst.SecretRequestAdvice;
import com.ybwh.outterapi.response.EncodeResponseBodyAdvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty(prefix = "openapi.secret", name = "enabled", havingValue = "true")
@EnableConfigurationProperties({OutterApiProperties.class})
public class OutterApiConfig {
    @Autowired
    private OutterApiProperties secretProperties;

    @Autowired
    private ObjectMapper objectMapper;


    @ConditionalOnMissingBean(DataCrypto.class)
    @Bean
    public DataCrypto dataCrypto() {
        return new DefaultDataCrypto();
    }


    @ConditionalOnMissingBean(AppInfoAccesser.class)
    @Bean
    public AppInfoAccesser appInfoAccesser() {
        // TODO
        return new AppInfoAccesser() {
            @Override
            public String getAppSecret(String appKey) {
                return "342356423";
            }
        };
    }

    @Bean
    public FilterRegistrationBean<HashCheckRequestInputStreamFilter> HashCheckRequestInputStreamFilter() {
        //通过FilterRegistrationBean实例设置优先级可以生效,通过@WebFilter无效
        FilterRegistrationBean<HashCheckRequestInputStreamFilter> bean = new FilterRegistrationBean<>();
        //注册自定义过滤器
        bean.setFilter(new HashCheckRequestInputStreamFilter(dataCrypto(), objectMapper));
        //过滤器名称
        bean.setName("HashCheckRequestInputStreamFilter");
        //过滤所有路径
        bean.addUrlPatterns("/*");
        //优先级，最顶级
        bean.setOrder(1);
        return bean;
    }

    @Bean
    public SecretRequestAdvice secretRequestAdvice(@Autowired AppInfoAccesser appInfoAccesser,@Autowired DataCrypto dataCrypto) {
        return new SecretRequestAdvice(objectMapper, dataCrypto, appInfoAccesser);
    }

    @Bean
    public EncodeResponseBodyAdvice encodeResponseBodyAdvice(@Autowired AppInfoAccesser appInfoAccesser,@Autowired DataCrypto dataCrypto) {
        return new EncodeResponseBodyAdvice(objectMapper, dataCrypto(), appInfoAccesser());
    }

}
